﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using WomanMotion.WebApi.Api.Utility;
using WomanMotion.WebApi.Infrastructure.UnifyResult;
using WomanMotion.WebApi.Infrastructure.YitId;
using WomanMotion.WebApi.Model.Common.FileUpload;
using WomanMotion.WebApi.Model.Dtos.Role;
using WomanMotion.WebApi.Service.IService;

namespace WomanMotion.WebApi.Api.Controllers
{
    /// <summary>
    /// 单文件上传
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [DescriptionName("单文件上传")]
    public class FileUploadController : BaseController
    {
        private IConfiguration _configuration;
        private readonly ICommonService _commonService;
        private readonly IHttpContextAccessor _httpContextAccessor;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="configuration"></param>
        public FileUploadController(ILogger<FileUploadController> logger, IConfiguration configuration, ICommonService commonService, IHttpContextAccessor httpContextAccessor) : base(logger)
        {
            this._configuration = configuration;
            this._commonService = commonService;
            this._httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 单文件上传
        /// </summary>
        /// <param name="file">文件</param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(SwaggerResultTemplate<FileInfoVM>), (int)HttpStatusCode.OK)]
        [DescriptionName("单文件上传")]
        public IResultOutput AnFileUpload(IFormFile file)
        {
            //取得文件的扩展名,并转换成小写
            string fileExtension = Path.GetExtension(file.FileName).ToLower();
            double filelen = file.Length / 1000000.0;
            double filelenmax = double.Parse(_configuration.GetSection("FileMax").Value);
            if (filelen > filelenmax)
            {
                return ResultOutput.NotOk("文件大小超出限制");
            }
            var filects = _configuration.GetSection("FileExtension").Get<FileExtension>();
            var isok = filects.Extension.Find(t => t == fileExtension);
            if (isok == null)
            {
                return ResultOutput.NotOk("不能上传此类型文件");
            }
            var res = _commonService.FileUpload(file);
            if (res != null)
            {
                return ResultOutput.Ok(res, "上传成功");
            }
            else
            {
                return ResultOutput.NotOk("上传失败");
            }
        }
    }
}